<template>
  <div class="container">
    <div class="title" v-if="!editMaintenanceId">新建{{ editMaintenanceId }}</div>
    <div class="title" v-else>
      <span>修改</span> <span class="back" @click="back"> <i class="iconfont icon-fanhui"></i> 返回 </span>
    </div>

    <div class="wrap">
      <el-row>
        <el-col :lg="16" :md="20" :sm="24" :xs="24">
          <el-form :model="maintenance" status-icon ref="form" label-width="150px" @submit.prevent :rules="rules">
            <!--            <el-form-item label="受理表ID" prop="accept_id">-->
            <!--              <el-input v-model="maintenance.accept_id" readonly placeholder="请填写受理表ID"></el-input>-->
            <!--            </el-form-item>-->

            <el-form-item v-if="editMaintenanceId" label="工单序号" prop="work_number">
              <el-input v-model="maintenance.work_number" disabled readonly></el-input>
            </el-form-item>
            <el-form-item label="受理序号" prop="order_number">
              <el-input v-model="maintenance.order_number" disabled readonly placeholder="请填写受理序号"></el-input>
            </el-form-item>
            <el-form-item label="受理时间" prop="order_time">
              <el-date-picker
                style="width: 100%"
                v-model="maintenance.order_time"
                type="datetime"
                placeholder="请填写受理时间"
              >
              </el-date-picker>
              <!--                <el-input v-model="maintenance.order_time" placeholder="请填写受理时间"></el-input>-->
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="maintenance.username" placeholder="请填写用户名"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="maintenance.phone" placeholder="请填写联系电话"></el-input>
            </el-form-item>
            <el-form-item label="终端类型" prop="type">
              <el-input v-model="maintenance.type" placeholder="请填写终端类型"></el-input>
            </el-form-item>
            <el-form-item label="型号颜色" prop="model">
              <el-input v-model="maintenance.model" placeholder="请填写型号颜色"></el-input>
            </el-form-item>
            <el-form-item label="维修性质" prop="nature">
              <el-input v-model="maintenance.nature" placeholder="请填写维修性质"></el-input>
            </el-form-item>
            <el-form-item label="本机号码" prop="local_number">
              <el-input v-model="maintenance.local_number" placeholder="请填写本机号码"></el-input>
            </el-form-item>
            <el-form-item label="机身号码" prop="serial_no">
              <el-input v-model="maintenance.serial_no" placeholder="请填写机身号码"></el-input>
            </el-form-item>
            <el-form-item label="附件" prop="file">
              <el-upload
                ref="uploadRef"
                v-model="maintenance.file"
                class="upload-demo"
                action="http://localhost:5000/cms/file"
                :on-preview="methods.handlePreview"
                :on-remove="methods.handleRemove"
                :on-change="methods.handleChange"
                :before-remove="methods.beforeRemove"
                multiple
                :limit="3"
                :on-exceed="methods.handleExceed"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
              <!--              <el-input v-model="maintenance.file" placeholder="请填写附件"></el-input>-->
            </el-form-item>
            <el-form-item label="修理内容" prop="content">
              <el-input v-model="maintenance.content" placeholder="请填写修理内容"></el-input>
            </el-form-item>
            <el-form-item label="更换配件" prop="re_accessories">
              <el-input v-model="maintenance.re_accessories" placeholder="请填写更换配件"></el-input>
            </el-form-item>
            <el-form-item label="配件费" prop="accessory_amount">
              <el-input v-model="maintenance.accessory_amount" placeholder="请填写配件费"></el-input>
            </el-form-item>
            <el-form-item label="工时费" prop="work_amount">
              <el-input v-model="maintenance.work_amount" placeholder="请填写工时费"></el-input>
            </el-form-item>
            <el-form-item label="合计" prop="total_amount">
              <el-input v-model="maintenance.total_amount" placeholder="请填写合计"></el-input>
            </el-form-item>
            <el-form-item label="所修项目保用期" prop="shelf">
              <el-date-picker
                v-model="maintenance.shelf"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
              >
              </el-date-picker>
              <!--                <el-input v-model="maintenance.shelf" placeholder="请填写所修项目保用期"></el-input>-->
            </el-form-item>

            <el-form-item class="submit">
              <el-button type="primary" @click="submitForm">保 存</el-button>
              <el-button @click="resetForm">重 置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import maintenanceModel from '@/model/maintenance'
import acceptModel from '@/model/accept'
import { useRoute } from 'vue-router'
import router from '@/router'

export default {
  props: {
    editMaintenanceId: {
      type: Number,
      default: null,
    },
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
    }
  },
  setup(props, context) {
    const uploadRef = ref(null)
    const fileList = ref([])

    const form = ref(null)
    const loading = ref(false)
    const route = useRoute()
    const maintenance = reactive({
      work_number: '',
      accept_id: '',
      order_number: '',
      order_time: '',
      username: '',
      phone: '',
      type: '',
      model: '',
      nature: '',
      local_number: '',
      serial_no: '',
      file: '',
      content: '',
      re_accessories: '',
      accessory_amount: '',
      work_amount: '',
      total_amount: '',
      shelf: '',
    })

    const methods = {
      handleRemove(file, fileListp) {
        fileList.value = fileListp
        console.log(file, fileListp)
      },
      handleChange(file, fileListp) {
        fileList.value = fileListp
        console.log(file, fileListp)
      },
      handlePreview(file) {
        downloadFile(file.response[0].url, file.name)
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`,
        )
      },
      // beforeRemove(file,fileListp) {
      //   return this.$confirm(`确定移除 ${file.name}？`)
      // }
    }
    const downloadFile = (u, n) => {
      const xml = new XMLHttpRequest()
      xml.open('GET', u, true)
      xml.responseType = 'blob'
      xml.onload = function () {
        const url = window.URL.createObjectURL(xml.response)
        const a = document.createElement('a')
        a.href = url
        a.download = n
        a.click()
      }
      xml.send()
    }

    const listAssign = (a, b) => Object.keys(a).forEach(key => {
      a[key] = b[key] || a[key]
    })

    /**
     * 表单规则验证
     */
    const { rules } = getRules()

    onMounted(async () => {
      if (props.editMaintenanceId) {
        getMaintenance()
      }
      // accept_id: route.query.id, order_number: route.query.order_number,
      // await acceptModel.getAccept(r)
      const ac_id = route.query.id
      if (ac_id) {
        const r = await acceptModel.getAccept(ac_id)
        maintenance.accept_id = ac_id
        if (!maintenance.order_number) {
          maintenance.order_number = r.order_number
        }
        if (!maintenance.order_time) {
          maintenance.order_time = r.order_time
        }
        if (!maintenance.username) {
          maintenance.username = r.username
        }
        if (!maintenance.phone) {
          maintenance.phone = r.phone
        }
        if (!maintenance.type) {
          maintenance.type = r.type
        }
        if (!maintenance.model) {
          maintenance.model = r.model
        }
        if (!maintenance.nature) {
          maintenance.nature = r.nature
        }
        if (!maintenance.local_number) {
          maintenance.local_number = r.local_number
        }
        if (!maintenance.serial_no) {
          maintenance.serial_no = r.serial_no
        }
        if (!maintenance.file) {
          maintenance.file = r.file
          fileList.value = JSON.parse(maintenance.file)
        }
      }
    })

    const uploadClearFile = () => {
      fileList.value = []
      uploadRef.value.clearFiles()
    }

    const getMaintenance = async () => {
      loading.value = true
      const res = await maintenanceModel.getMaintenance(props.editMaintenanceId)
      listAssign(maintenance, res)

      fileList.value = JSON.parse(maintenance.file)

      loading.value = false
    }

    // 重置表单
    const resetForm = () => {
      form.value.resetFields()
    }

    const submitForm = async formName => {
      form.value.validate(async valid => {
        if (valid) {
          let res = {}

          let params = { ...maintenance }
          if (fileList.value.length > 0) {
            params = { ...maintenance, ...{ file: JSON.stringify(fileList.value) } }
          }

          if (props.editMaintenanceId) {
            res = await maintenanceModel.editMaintenance(props.editMaintenanceId, params)
            if (res.code === 10200) {
              ElMessage.error('请将信息填写完整')
            } else {
              context.emit('editClose')
            }
          } else {
            res = await maintenanceModel.createMaintenance(params)
            console.log(res.code)
            if (res.code === 10200) {
              ElMessage.error('请将信息填写完整')
            } else {
              resetForm(formName)
              router.push({ path: '/maintenance/list' })
            }
          }
          if (res.code < window.MAX_SUCCESS_CODE) {
            uploadClearFile()
            ElMessage.success(`${res.message}`)
          }
        } else {
          console.error('error submit!!')
          ElMessage.error('请将信息填写完整')
        }
      })
    }

    const back = () => {
      context.emit('editClose')
    }

    return {
      back,
      maintenance,
      form,
      rules,
      resetForm,
      submitForm,
      methods,
      fileList,
      uploadRef,
    }
  },
}

/**
 * 表单验证规则
 */
function getRules() {
  /**
   * 验证回调函数
   */
  const checkInfo = (rule, value, callback) => {
    if (!value) {
      callback(new Error('信息不能为空'))
    }
    callback()
  }
  const rules = {
    accept_id: [{ validator: checkInfo, trigger: 'blur', required: true }],
    order_number: [{ validator: checkInfo, trigger: 'blur', required: true }],
    order_time: [{ validator: checkInfo, trigger: 'blur', required: true }],
    username: [{ validator: checkInfo, trigger: 'blur', required: true }],
    phone: [{ validator: checkInfo, trigger: 'blur', required: true }],
    type: [{ validator: checkInfo, trigger: 'blur', required: true }],
    model: [{ validator: checkInfo, trigger: 'blur', required: true }],
    nature: [{ validator: checkInfo, trigger: 'blur', required: true }],
    local_number: [{ validator: checkInfo, trigger: 'blur', required: true }],
    serial_no: [{ validator: checkInfo, trigger: 'blur', required: true }],
    content: [{ validator: checkInfo, trigger: 'blur', required: true }],
    re_accessories: [{ validator: checkInfo, trigger: 'blur', required: true }],
    accessory_amount: [{ validator: checkInfo, trigger: 'blur', required: true }],
    work_amount: [{ validator: checkInfo, trigger: 'blur', required: true }],
    total_amount: [{ validator: checkInfo, trigger: 'blur', required: true }],
    shelf: [{ validator: checkInfo, trigger: 'blur', required: true }],
  }
  return { rules }
}
</script>

<style lang="scss" scoped>
.container {
  .title {
    height: 59px;
    line-height: 59px;
    color: $parent-title-color;
    font-size: 16px;
    font-weight: 500;
    text-indent: 40px;
    border-bottom: 1px solid #dae1ec;

    .back {
      float: right;
      margin-right: 40px;
      cursor: pointer;
    }
  }

  .wrap {
    padding: 20px;
  }

  .submit {
    float: left;
  }
}
</style>
